import re
import random
import threading
from flask import session
from flask import jsonify
from pypinyin import pinyin, Style
from functools import wraps
import uuid
import hashlib
import hmac


class Singleton(type):
    _instance_lock = threading.RLock()

    def __call__(cls, *args, **kwargs):
        with Singleton._instance_lock:
            if hasattr(cls, "_instance"):
                return cls._instance
            else:
                cls._instance = super().__call__(*args, **kwargs)
                return cls._instance


class JsonResult:
    @classmethod
    def ok(cls, msg, data=None):
        return jsonify({"success": True, "msg": msg, "data": data}), 200

    @classmethod
    def error(cls, msg):
        return jsonify({"msg": msg}), 555

    @classmethod
    def auth(cls, msg, data=None):
        return jsonify({"success": False, "msg": msg, "data": data}), 401
    

def phone_check(phone_num):
    pattern = re.compile(
        r"^(13[0-9]|14[0|5|6|7|9]|15[0|1|2|3|5|6|7|8|9]|"
        r"16[2|5|6|7]|17[0|1|2|3|5|6|7|8]|18[0-9]|"
        r"19[1|3|5|6|7|8|9])\d{8}$"
    )
    if pattern.search(phone_num):
        return True
    else:
        return False


def rand_num(len=4):
    res = ""
    for i in range(len):
        res += str(random.randint(0, 9))
    return res


def login_required(func):
    @wraps(func)
    def inner(*args, **kwargs):  
        phone_num = session.get("phone_num")
        if not phone_num:
            return JsonResult.error("您还未登录!或者登录状态已失效请重新登录！")
        else:
            return func(*args, **kwargs)

    return inner


def get_account_id(game_name):
    initials = pinyin(game_name[:2], style=Style.FIRST_LETTER)
    # 将结果转换为单一字符串
    initials_str = ''.join([item[0] for item in initials])
    return initials_str + str(uuid.uuid4().int)[-7:-1]

def get_en_name(game_name):
    initials = pinyin(game_name, style=Style.FIRST_LETTER)
    # 将结果转换为单一字符串
    initials_str = ''.join([item[0] for item in initials])    
    return initials_str

# 签名订单ID
def sign_order_id(order_id):
    hmac_obj = hmac.new(b"linglongwang", order_id.encode("utf-8"), hashlib.sha256)
    signature = hmac_obj.hexdigest()
    return signature


# 校验签名并获取订单ID
def verify_signature(order_id, key_id):
    expected_signature = sign_order_id(order_id)
    is_valid_signature = hmac.compare_digest(key_id, expected_signature)
    if is_valid_signature:
        return True
    else:
        return False
